import path from 'path'
import gulp from 'gulp'
import del from 'del'
import gulpLoadPlugins from 'gulp-load-plugins'
import runSequence from 'run-sequence'
import browserSync from 'browser-sync'
import proxy from 'http-proxy-middleware';
import config from './config/config.js'

const $ = gulpLoadPlugins();
const reload = browserSync.reload;

gulp.task("lint", () => {
    gulp.src(config.dev.scripts)
        .pipe($.if("*.ts",$.typescript()))
        .pipe($.eslint())
        .pipe($.eslint.format())
        .pipe($.if(!browserSync.active, $.eslint.failAfterError()))
})

gulp.task("scripts", () => {
    gulp.src(config.dev.scripts)
        .pipe($.sourcemaps.init())
        .pipe($.if("*.ts", $.typescript()))
        .pipe($.babel())
        .pipe($.uglify())
        .pipe($.size({title: "scripts"}))
        .pipe($.sourcemaps.write("./"))
        .pipe($.if('*.js', $.size({title: 'scripts', showFiles: true})))
        .pipe(gulp.dest(config.dist.scripts))
})

gulp.task("images", () => {
    gulp.src(config.dev.images)
        .pipe($.cache($.imagemin({
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest(config.dist.images))
        .pipe($.size({title: "images"}))
})

gulp.task("styles", () => {
    gulp.src(config.dev.styles)
        .pipe($.sourcemaps.init())
        .pipe($.less())
        .pipe($.autoprefixer(config.AUTOPREFIXER_BROWSERS))
        .pipe($.if("*.css", $.cssnano()))
        .pipe($.sourcemaps.write("./"))
        .pipe($.if('*.css', $.size({title: 'styles', showFiles: true})))
        .pipe(gulp.dest(config.dist.styles))
})

gulp.task("htmls", () => {
    gulp.src(config.dev.htmls)
    .pipe($.if('*.html', $.htmlmin({
        removeComments: true
    })))
    .pipe($.if('*.html', $.size({title: 'html', showFiles: true})))
    .pipe(gulp.dest(config.dist.htmls));
})

gulp.task('clean', () => {
    del(config.dist.root, {dot: true})
})

gulp.task('default', ["clean"] , cb => {
    runSequence(
        ['styles','lint', 'htmls', 'scripts', 'images'],
        cb
    )
})

gulp.task('serve', ['default'], () => {
    browserSync({
        notify: false,
        scrollElementMapping: ['main', '.mdl-layout'],
        logPrefix: 'web-starter',
        server: {
            baseDir: 'dist',
            middleware: [proxy(['/api'], {target: 'http://localhost:8080', changeOrigin: true})],
        },
        port: 3000
    })

    gulp.watch(config.watch.htmls, ['htmls', reload])
    gulp.watch(config.watch.images, ['images', reload])
    gulp.watch(config.watch.styles, ['styles', reload])
    gulp.watch(config.watch.scripts, ['lint','scripts', reload])
})